package com.hiv.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import com.google.common.collect.Lists;
import com.hiv.common.PageInfo;
import com.hiv.common.param.page.PageQueryPatientParam;
import com.hiv.common.utils.AssertUtil;
import com.hiv.mapper.HospitalMapper;
import com.hiv.mapper.PatientMapper;
import com.hiv.mapper.SamplingRecordMapper;
import com.hiv.mapper.domain.Admin;
import com.hiv.mapper.domain.Hospital;
import com.hiv.mapper.domain.Patient;
import com.hiv.mapper.domain.SamplingRecord;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 患者Service业务层处理
 *
 * @author zhanghong
 * @date 2022-09-20
 */
@Service
public class PatientService {
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private HospitalMapper hospitalMapper;
    @Autowired
    private SamplingRecordMapper samplingRecordMapper;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private AdminAccountService adminAccountService;

    /**
     * 分页查询
     * @param param
     * @return
     */
    public PageInfo<Patient> pageQuery(Admin admin, PageQueryPatientParam param) {
        if (admin != null && admin.getType() == 1) {
            //质控中心-则查询质控中心下所有医院的采样数据
            List<Hospital> hospitals = hospitalMapper.listByParentId(admin.getHospitalId());
            if (CollectionUtils.isEmpty(hospitals)) {
                return new PageInfo<>(param.getPageNum(), param.getPageSize(), Lists.newArrayList(), 0);
            }
            param.setHospitalId(null);
            List<Long> yiYuanIds = hospitals.stream().map(Hospital::getId).collect(Collectors.toList());
            param.setHospitalIdList(yiYuanIds);
        }
        //long count = patientMapper.pageCount(param);
        //List<Patient> list = patientMapper.pageQuery(param, param.getPageSize(), param.fetchOffSet());

        List<Patient> patients = patientMapper.listQuery(param);
        if (CollectionUtils.isEmpty(patients)) {
            return new PageInfo<>(param.getPageNum(), param.getPageSize(), Lists.newArrayList(), 0);
        }

        List<Patient> distinctList = Lists.newArrayList();
        Map<String, List<Patient>> map = patients.stream().collect(Collectors.groupingBy(Patient::getAntiviralCode));
        map.forEach((key, values)->{
            if (CollectionUtils.isNotEmpty(values)) {
                Patient patient = values.stream().sorted(Comparator.comparing(Patient::getCreateTime).reversed()).findFirst().orElseGet(null);
                if (patient != null) {
                    distinctList.add(patient);
                }
            }
        });
        if (CollectionUtils.isEmpty(distinctList)) {
            return new PageInfo<>(param.getPageNum(), param.getPageSize(), Lists.newArrayList(), 0);
        }
        long count = distinctList.stream().count();
        List<Patient> list = ListUtil.page(param.getPageNum() - 1, param.getPageSize(), distinctList);
        for (Patient patient : list) {
            if (patient.getAntiviralCode() != null) {
                // 患者检测数据
                List<SamplingRecord> samplingRecords = samplingRecordMapper.inspectionListByAntiviralCode(patient.getAntiviralCode());
                if (CollectionUtils.isNotEmpty(samplingRecords)) {
                    //患者检测数量统计
                    patient.setInspectionCount(samplingRecords.size());
                    //患者检测医院数量统计
                    Set<Long> hospitalSet = samplingRecords.stream().map(SamplingRecord::getHospitalId).collect(Collectors.toSet());
                    patient.setInspectionHospitalCount(hospitalSet.size());
                }
            }
        }
        return new PageInfo<>(param.getPageNum(), param.getPageSize(), list, count);
    }

    /**
     * 查询患者
     *
     * @param id 患者主键
     * @return 患者
     */
    public Patient getById(Long id) {
        Patient patient = patientMapper.selectById(id);
        if (patient.getAntiviralCode() != null) {
            // 患者检测数据
            List<SamplingRecord> samplingRecords = samplingRecordMapper.inspectionListByAntiviralCode(patient.getAntiviralCode());
            if (CollectionUtils.isNotEmpty(samplingRecords)) {
                //患者检测数量统计
                patient.setInspectionCount(samplingRecords.size());
                //患者检测医院数量统计
                Set<Long> hospitalSet = samplingRecords.stream().map(SamplingRecord::getHospitalId).collect(Collectors.toSet());
                patient.setInspectionHospitalCount(hospitalSet.size());
            }
        }
        return patient;
    }

    /**
     * 查询患者列表
     *
     * @param patient 患者
     * @return 患者
     */
    public List<Patient> selectList(Patient patient) {
        return patientMapper.selectList(patient);
    }

    /**
     * 保存患者
     *
     * @param patient 患者
     * @return 结果
     */
    public Boolean save(Patient patient) {
        if (patient.getId() != null) {
            patientMapper.update(patient);
            return true;
        }
        patientMapper.insert(patient);
        return true;
    }

    /**
     * 批量删除患者
     *
     * @param ids 需要删除的患者主键
     * @return 结果
     */
    public Boolean deleteByIds(String ids) {
        patientMapper.deleteByIds(Convert.toStrArray(ids));
        return true;
    }

    /**
     * 查询患者授权检测列表
     * @param id
     * @return
     */
    public List<SamplingRecord> getInspectionList(long id) {
        Patient patient = patientMapper.selectById(id);
        AssertUtil.assertNotNull(patient, "患者不存在");
        // 患者检测数据
        List<SamplingRecord> list = samplingRecordMapper.inspectionListByAntiviralCode(patient.getAntiviralCode());
        list.stream().forEach(item -> buildInfo(item));
        return list;
    }

    /**
     * 组装信息
     * @param item
     */
    private void buildInfo(SamplingRecord item) {
        item.setHospitalName(hospitalService.getHospitalName(item.getHospitalId()));
        item.setSamplerName(adminAccountService.getUserName(item.getSamplerId()));
        item.setStoragerName(adminAccountService.getUserName(item.getStoragerId()));
        item.setInspectorName(adminAccountService.getUserName(item.getInspectorId()));
    }

    /**
     * 查询患者授权检测医院列表
     * @param id
     * @return
     */
    public List<Hospital> getInspectionHospitalList(long id) {
        Patient patient = patientMapper.selectById(id);
        AssertUtil.assertNotNull(patient, "患者不存在");
        // 患者检测数据
        List<SamplingRecord> samplingRecords = samplingRecordMapper.inspectionListByAntiviralCode(patient.getAntiviralCode());
        if (CollectionUtils.isEmpty(samplingRecords)) {
            return Lists.newArrayList();
        }

        //患者检测医院数量统计
        Set<Long> hospitalSet = samplingRecords.stream().map(SamplingRecord::getHospitalId).collect(Collectors.toSet());
        return hospitalMapper.queryByIds(hospitalSet);
    }
}
